package com.ks.test.app;

import javassist.ClassPool;
import javassist.bytecode.Bytecode;
import javassist.bytecode.ClassFile;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.MethodInfo;
import javassist.bytecode.Mnemonic;

public class Demo4 {

    public static void main(String[] args) throws Exception {

        ClassPool classPool = ClassPool.getDefault();
        ClassFile classFile = classPool.get("com.ks.test.app.Point").getClassFile();

        Bytecode bytecode = new Bytecode(classFile.getConstPool());
        bytecode.addLload(0);
        // addInvokespecial
        // 调用 java.lang.Object <init> 方法
        bytecode.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
        bytecode.addReturn(null);

        MethodInfo methodInfo = new MethodInfo(classFile.getConstPool(), MethodInfo.nameInit, "()V");
        methodInfo.setCodeAttribute(bytecode.toCodeAttribute());
        classFile.addMethod(methodInfo);

        CodeIterator codeIterator = bytecode.toCodeAttribute().iterator();

        while (codeIterator.hasNext()) {
            int index = codeIterator.next();
            int op = codeIterator.byteAt(index);
            System.out.println(Mnemonic.OPCODE[op]);
        }
    }
}
